package vn.pyco.prez.tapestry.components;

import java.util.List;

import org.apache.tapestry5.Link;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionAttribute;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.cometd.bayeux.server.ServerSession;

import vn.pyco.prez.PrezConstants;
import vn.pyco.prez.PrezConstants.Steps;
import vn.pyco.prez.dao.DaoManager;
import vn.pyco.prez.model.Slide;
import vn.pyco.prez.tapestry.pages.Index;
import vn.pyco.prez.tapestry.pages.Remote;
import vn.pyco.prez.tapestry.services.AppHelper;

@Import(
	stack=PrezConstants.COMETD_JSSTACK,
	library={
			"${prez.scripts}/jquery.cometd.settings.js",
			"${prez.scripts}/jquery.cometd.prezviewer.js"
	}
)
public class PrezViewer {
	@SuppressWarnings("unused")
	@SessionAttribute(PrezConstants.SESSION_STEP)
	private Steps _currentStep;
	
	@SessionAttribute(PrezConstants.SESSION_TASK_ID)
	private String _taskId;
	
	@InjectService("slideManager")
	private DaoManager<List<Slide>> _slideManager;

	@InjectService("clientSessionManager")
	private DaoManager<ServerSession> _clientSessionManager;
	
	@SuppressWarnings("unused")
	@Property
	private List<Slide> _slides;
	
	private Link _remoteControlLink;
	
	@Inject
	private JavaScriptSupport _jsSupport;	
	
	@Inject
    private AppHelper _appHelper; 
	
	@Inject
	@Symbol(SymbolConstants.PRODUCTION_MODE)
	private boolean _productionMode;
	
	@SetupRender
	public void setupRender(){
		_slides = _slideManager.getById(_taskId);
		_remoteControlLink = _appHelper.getPageLink(Remote.class, _taskId);
	}

	@AfterRender
	public void afterRender(){
		_jsSupport.addScript("CometSettings.init('%s','%s','%s','%s');",
				_appHelper.getFQNRootUrl(Boolean.FALSE) + PrezConstants.COMETD_URL,
				_productionMode ? "warn" : "info",
				_taskId,
				"null"
				);
		_jsSupport.addScript("CometPrezViewer.init();");
	}	
	
	/**
	 * @return the remoteControlLink
	 */
	public String getRemoteControlLink() {
		return _remoteControlLink.toAbsoluteURI();
	}
	
	@OnEvent(value="newPrez")
	public Class<?> clearDatas(){
		_currentStep = Steps.SELECT;
		_slideManager.delete(_taskId);
		_clientSessionManager.delete(_taskId);
		return Index.class;
	}

}
